package com.hms.service.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hms.dao.IAdminDao;
import com.hms.entity.Admin;
import com.hms.entity.Role;

@Service("adminDetailsService")
@Transactional
public class AdminDetailsService implements UserDetailsService {

	@Resource
	IAdminDao adminDao;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		Admin admin = adminDao.getAdminByuUserName(username);
		if (null == admin) {
			throw new UsernameNotFoundException("管理员: " + username + " 不存在");
		}
		admin.setAuthorities(getGrantedAuthorities(admin));
		return admin;
	}

	/**
	 * @param admin
	 *            根据用户获取权限
	 * @return 管理员角色
	 */
	public Collection<GrantedAuthority> getGrantedAuthorities(Admin admin) {
		Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();
		for (Role role : admin.getRoleSet()) {
			grantedAuthorities.add(new GrantedAuthorityImpl(role.getValue()));
		}
		return grantedAuthorities;
	}
}
